package com.ysd.utils;

import java.util.ArrayList;
import java.util.List;

import com.ysd.entity.Modules;

public class BuildTree {

	List<Modules> TreeNodes = new ArrayList<>();

	public List<Modules> buildTree(List<Modules> TreeNodes) {
		BuildTree treeBuilder = new BuildTree(TreeNodes);
		return treeBuilder.buildJSONTree();
	}

	public BuildTree() {
	}

	public BuildTree(List<Modules> TreeNodes) {
		super();
		this.TreeNodes = TreeNodes;
	}

	// 构建JSON树形结构
	public List<Modules> buildJSONTree() {
		List<Modules> TreeNodeTree = buildTree();
		return TreeNodeTree;
	}

	// 构建树形结构
	public List<Modules> buildTree() {
		List<Modules> treeTreeNodes = new ArrayList<>();
		// 获取所有根节点
		List<Modules> rootTreeNodes = getRootTreeNodes();
		// 获取每个根节点
		for (Modules rootTreeNode : rootTreeNodes) {
			try {
				// 递归这个根节点的子节点
				buildChildTreeNodes(rootTreeNode);

				// 用list来存放每个根节点
				treeTreeNodes.add(rootTreeNode);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return treeTreeNodes;
	}

	// 递归子节点
	public void buildChildTreeNodes(Modules TreeNode) {
		List<Modules> children = getChildTreeNodes(TreeNode);
		if (!children.isEmpty()) {
			for (Modules child : children)
				try {
					buildChildTreeNodes(child);
				} catch (Exception e) {
					e.printStackTrace();
				}
			TreeNode.setChildren(children);
		}
	}

	/**
	 * 获取父节点下所有的子节点
	 * 
	 * @param pTreeNode
	 * @return
	 */
	public List<Modules> getChildTreeNodes(Modules pTreeNode) {
		List<Modules> childTreeNodes = new ArrayList<>();

		for (Modules n : TreeNodes) {
			// if (pTreeNode.getCode().equals(n.getPcode())) {
			if (pTreeNode.getId().equals(n.getParentId())) {
				childTreeNodes.add(n);
			}
		}
		return childTreeNodes;
	}

	// 判断是否为根节点
	public boolean rootTreeNode(Modules TreeNode) {
		boolean isRootTreeNode = true;
		for (Modules n : TreeNodes) {
			// if (TreeNode.getPcode().equals(n.getCode())) {
			if (TreeNode.getParentId().equals(n.getId())) {
				isRootTreeNode = false;
				break;
			}
		}
		return isRootTreeNode;
	}

	// 获取集合中所有的根节点
	public List<Modules> getRootTreeNodes() {
		List<Modules> rootTreeNodes = new ArrayList<>();
		for (Modules n : TreeNodes) {
			if (rootTreeNode(n)) {
				rootTreeNodes.add(n);
			}
		}
		return rootTreeNodes;
	}
}